package com.example.activitispringbootstest.service.impl;

import com.example.activitispringbootstest.dao.LeaveBillMapper;
import com.example.activitispringbootstest.dto.ApproveDTO;
import com.example.activitispringbootstest.entity.LeaveBillDO;
import com.example.activitispringbootstest.service.ProcessTaskService;
import com.example.activitispringbootstest.util.SecurityUser;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author swxu_2005@163.com
 * @date 2019/2/3
 */
@Service
public class LeaveBillServiceImpl {

  private static final String KEY = "leave_demo";

  @Autowired
  private LeaveBillMapper leaveBillMapper;

  @Autowired
  private ProcessTaskService processTaskService;

  /**
   * 暂存请假单
   */
  public void insert(LeaveBillDO leaveBill) {
    leaveBillMapper.insert(leaveBill);
  }

  /**
   * 保存请假单，并提交申请
   */
  public void insertAndStartProcess(LeaveBillDO leaveBill) {
    if (leaveBill.getId() == null) {
      leaveBillMapper.insert(leaveBill);
    }

    Map<String, Object> vars = new HashMap<>();
    vars.put("days", leaveBill.getDays());
    processTaskService.startProcess(leaveBill, KEY, vars);
    // 记得更新
    leaveBillMapper.updateById(leaveBill);

    // 本工作流启动后，需要申请者马上完成第一个节点任务：员工申请
    List<Task> tasksTodo = processTaskService.queryTodoTasks(KEY);
    processTaskService.completeTask(tasksTodo.get(0).getId());
  }

  /**
   * 主管签收
   */
  public void zgClaim(String taskId) {
    processTaskService.claimTask(taskId);
  }

  /**
   * 各级审批：主管、经理、老板
   */
  public void approve(ApproveDTO approve) {
    // 根据当前用户的角色，确定map中审批结果的key
    String resultKey = SecurityUser.getRole() + "Result";
    Map<String, Object> vars = new HashMap<>();
    vars.put(resultKey, approve.getResult());
    processTaskService.completeTask(approve.getTaskId(), approve.getProcessInstanceId(), approve.getComment(), vars);
  }

  /**
   * 请假单查询
   * @param id    业务主键ID
   */
  public void getLeaveBill(Long id) {
    // 查询业务实例
    LeaveBillDO leaveBill = leaveBillMapper.selectById(id);

    // 查询与该业务实例相关的流程审批记录
    // TODO
  }


}
